import { Service } from "egg";
import { DrugProps } from "../model/Drug";
import { IndexCondition } from "../common";
// import { Types } from "mongoose";

export default class DrugService extends Service {
  /**
   * 根据传入名称查询
   */
  public findByName(condition) {
    return this.ctx.model.Drug.findOne(condition);
  }

  /**
   * 查找列表
   * @param {IndexCondition} condition 查询条件
   */
  public async findList(condition: IndexCondition) {
    const { ctx } = this;
    const { select, pageSize, pageIndex, find } = condition;
    const skip = pageIndex && pageSize ? pageIndex * pageSize : 0;
    const res = await ctx.model.Drug.find(find ? find : {})
      .select(select)
      .skip(skip)
      .limit(typeof pageSize === "number" ? pageSize : 10)
      .lean();
    const count = await ctx.model.Drug.find(find ? find : {}).count();
    return {
      count,
      list: res,
      pageSize: pageSize !== undefined ? pageSize : 10,
      pageIndex: pageIndex !== undefined ? pageIndex + 1 : 1,
    };
  }

  /**
   * 添加数据
   * @param data 测试数据
   */
  public async add(data) {
    const { ctx } = this;
    const { name, price, entryPrice, factory, brand, standard } = data;
    // 品牌创建
    let _brand = await ctx.service.brand.findByName(brand);
    if (!_brand) {
      _brand = await ctx.service.brand.add({ brand });
    }
    // 规格创建
    let _standard = await ctx.service.standard.findByName(standard);
    if (!_standard) {
      _standard = await ctx.service.standard.add({ standard });
    }
    //  公司创建
    let _factory = await ctx.service.drugFactory.findByName(factory);
    if (!_factory) {
      _factory = await ctx.service.drugFactory.add({
        name: factory,
      });
    }
    // 药品添加
    const _data: Partial<DrugProps> = {
      name,
      price,
      entryPrice,
      ...{
        brand: _brand.brand,
        standard: _standard.standard,
        factory: _factory.name,
      },
    };
    return await ctx.model.Drug.create(_data);
  }
}
